<template>
  <div class="parent">
    <!-- 页面名称 -->
    <div class="header">
      <span>字典信息维护</span>
    </div>
    <!-- <h1>{{ form1 }}</h1> -->
    <!-- 内容 -->
    <el-container class="body">
      <!-- 树形 -->
      <el-aside width="200px" class="mainaside">
        <div class="user_tree">
          <el-tree
            class="el-tree"
            ref="treeRef"
            :props="props"
            :data="treeDate"
            highlight-current="true"
            node-key="fId"
            check-strictly="true"
            @current-change="selectTable"
          />
          <!-- <ul>
            <li v-for="i in treename" :key="i" @click="selectTable(i.fId)">
              {{ i.fDdcName }}
            </li>
          </ul> -->
        </div>
      </el-aside>
      <el-main class="mainmain">
        <!-- 新增按钮及查询 -->
        <div class="firsthe">
          <el-button type="primary" class="add" @click="addDate(true, null)"
            >新增</el-button
          >
          <!-- 弹框内容 -->
          <el-dialog
            v-model="dialogFormVisible"
            :title="isAdd ? '新增字典信息' : '编辑字典分类'"
            :close-on-click-modal="false"
            destroy-on-close
            :width="500"
          >
            <el-form
              :model="form"
              :isAdd="newstate"
              :rules="pageData.formRules"
              label-width="100px"
              status-icon
            >
              <el-form-item
                label="类别名称："
                prop="fDdcCode"
                :label-width="formLabelWidth"
              >
                <!-- <el-input v-model="form.fDdcId" autocomplete="off" /> -->
                <el-select
                  v-model="form.fDdcName"
                  placeholder="请选择类别名称"
                  @change="curoption"
                >
                  <el-option
                    v-for="item in treename"
                    :key="item.fId"
                    :label="item.fDdcName"
                    :value="item.fDdcName"
                  />
                </el-select>
              </el-form-item>
              <!-- <h1>{{treename}}</h1> -->
              <el-form-item
                label="类别编号："
                :label-width="formLabelWidth"
                prop="fDdcCode"
              >
                <el-input
                  v-model="form.fDdcCode"
                  autocomplete="off"
                  placeholder="自动填充"
                  :disabled="!pageData.isAdd || pageData.isAdd"
                />
              </el-form-item>
              <el-form-item
                label="字典编号："
                :label-width="formLabelWidth"
                prop="fDdCode"
              >
                <el-input
                  v-model="form.fDdCode"
                  autocomplete="off"
                  placeholder="请输入字典编号"
                />
              </el-form-item>
              <el-form-item
                label="字典名称："
                :label-width="formLabelWidth"
                prop="fDdName"
              >
                <el-input
                  v-model="form.fDdName"
                  autocomplete="off"
                  placeholder="请输入字典名称"
                />
              </el-form-item>

              <el-form-item label="录入人员：" :label-width="formLabelWidth">
                <el-input
                  v-model="form.fFullName"
                  autocomplete="off"
                  placeholder="自动填充"
                  :disabled="!pageData.isAdd || pageData.isAdd"
                />
              </el-form-item>
              <el-form-item label="录入时间：" :label-width="formLabelWidth">
                <el-input
                  v-model="form.fCreatorTime"
                  autocomplete="off"
                  placeholder="自动填充"
                  :disabled="!pageData.isAdd || pageData.isAdd"
                />
              </el-form-item>
              <el-form-item label="备注：" :label-width="formLabelWidth">
                <el-input v-model="form.fRemark" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="newadd"> 提交 </el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 弹框内容结束 -->

          <div class="search">
            <el-input
              v-model="pageData.queryParams.fDdCode"
              placeholder="请输入字典编码"
              clearable
              ><template #prepend>字典编码</template>
            </el-input>

            <el-input
              v-model="pageData.queryParams.fDdName"
              placeholder="请输入字典名称"
              clearable
              ><template #prepend>字典名称</template>
            </el-input>

            <el-button type="primary" plain @click="onHandleSearch"
              >搜索</el-button
            >
            <el-button type="warning" plain @click="onHandleReset"
              >重置</el-button
            >
          </div>
        </div>

        <!-- 主体表格 -->
        <el-table
          :data="pageData.tableParams.tableData"
          style="width: 100%"
          border
          v-loading="pageData.tableParams.tableLoading"
        >
          <!-- .filter((v) => v.fState != '20') -->
          <el-table-column
            fixed
            prop="fDdcCode"
            label="类别编号"
            min-width="120"
          />
          <el-table-column prop="fDdcName" label="类别名称" min-width="120" />
          <el-table-column prop="fDdCode" label="字典编号" min-width="120" />
          <el-table-column prop="fDdName" label="字典名称" min-width="120" />
          <el-table-column prop="fFullName" label="录入人员" min-width="120" />
          <el-table-column
            prop="fCreatorTime"
            label="录入时间"
            min-width="120"
          />
          <el-table-column prop="fState" label="状态" min-width="120">
            <template #="v">
              <span>{{
                v.row.fState == 0
                  ? "草稿"
                  : v.row.fState == 10
                  ? "审核中"
                  : v.row.fState == 20
                  ? "作废/删除"
                  : "审核通过"
              }}</span>
              <!-- <span>{{v.row.fState.filter((v) => v.fState != '20')}}</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="fRemark" label="备注" width="400" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="row">
              <el-button
                link
                type="primary"
                size="small"
                @click="addDate(false, row.row)"
                >编辑</el-button
              >

              <el-button
                link
                type="primary"
                size="small"
                @click="ddthedata(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 删除弹窗 -->
        <!-- <el-dialog
          v-model="centerDialogVisible"
          title="提示："
          width="30%"
          align-center
        >
          <span>
            是否确定删除该字典信息
          </span>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="sureDelete">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog> -->

        <!-- 分页查询 -->
        <el-col :span="24">
          <el-pagination
            style="margin-top: 20px"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="pageData.tableParams.pageSizeOptions"
            :current-page="pageData.queryParams.page"
            :page-size="pageData.queryParams.pageSize"
            :total="pageData.tableParams.totalCount"
            @current-change="onHandleCurrentChange"
            @size-change="onHandleSizeChange"
          >
          </el-pagination>
        </el-col>

        <!-- <button @click="hq">点击获取数据</button> -->
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { reactive, ref, nextTick, onMounted, toRefs } from "vue";
import {
  search,
  newPoints,
  deleteData,
  search_zdcategory,
  searchDetails,
  query_zdcategory,
  uppdata,
} from "@/api/basic/zdinfo";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import utils from "@/common/utils";
// import { search_zdcategory } from '@/api/basic/zdcategory';

export default {
  setup() {
    var fid = ref("");
    onMounted(() => {
      // console.log(getTableData)
      nextTick(getTableData);
      // updatepage();
      // hq()
      ffun();
    });

    // 树形侧边栏
    var treename = reactive([]);
    // const formLabelWidth  = '140px'

    //这里的"data"形参传受点击项的全部数据;
    // let props = reactive({
    //   children: "children",
    //   label: "label",
    // });

    const handleNodeClick = (data) => {
      //router.push(data.url); //本例中我们拿取url属性做跳转;
      //   console.log("点击打开参数");
    };
    let isAdd = ref(null);
    function addDate(ist, data) {
      dialogFormVisible.value = true;
      if (ist) {
        isAdd.value = true;
        for (let item in form) {
          form[item] = "";
        }
      } else {
        isAdd.value = false;
        // console.log("=====", data);
        for (let i in data) {
          form[i] = data[i];
        }
      }
    }
    const pageData = reactive({
      queryParams: {
        fDdcId: "3cdfe6cda341461dadc3ecc9a8dd1f48",
        page: 1,
        pageSize: 10,
        fDdCode: "",
        fDdName: "",
      },
      tableParams: {
        tableLoading: false,
        tableHeight: 0,
        pageSizeOptions: ["10", "15", "30", "50", "100", "200"],
        totalCount: 0,
        tableData: [],
      },
      selectRows: [],
      currentRow: {},
      formRules: {
        fDdcCode: [
          { required: true, message: "请输入字典类别编号", trigger: "blur" },
        ],
        fDdcName: [
          { required: true, message: "请输入字典类别名称", trigger: "blur" },
        ],
        fDdCode: [
          { required: true, message: "请输入字典类别名称", trigger: "blur" },
        ],
        fDdName: [
          { required: true, message: "请输入字典类别名称", trigger: "blur" },
        ],
      },
    });

    // 获取字典信息
    const getTableData = () => {
      pageData.tableParams.tableLoading = true;
      search(pageData.queryParams) //获取字典类别接口
        .then((res) => {
          console.log("查询数据的：", res);
          // 将获取的数据赋给table
          pageData.tableParams.tableData = res.list;
          pageData.tableParams.totalCount = res.totalCount;

          // 总条目数
          // if (res.data.list != null) {
          //   pageData.tableParams.totalCount = res.list.length;
          // } else {
          //   pageData.tableParams.totalCount = res.totalCount;
          // }

          pageData.tableParams.tableLoading = false;
        })
        .catch(() => {
          pageData.tableParams.tableLoading = false;
        });
    };

    function selectTable(res) {
      console.log("resresres", res);
      pageData.queryParams.fDdcId = res.fId;
      getTableData();
    }
    // 获取树形内容
    const treeRef = ref("");
    const treeDate = reactive([]);
    const props = {
      children: "children",
      label: "fDdcName",
    };
    const ffun = () => {
      query_zdcategory().then((res) => {
        console.log("查看字典分类的res:", res);
        treename.push(...res);
        treeDate.push(...res);
        // console.log("查看resssss111:", treeDate);
      });
    };
    // 遍历
    // const updatepage = () => {
    //   query_zdcategory().then((res) => {
    //     // console.log("查看字典分类的res:", res.data);
    //     treename.push(...res.data);
    //     console.log("查看treename1111:", treename);
    //   });
    // }; //树形内容结束

    // var form = reactive([])

    // 新增弹窗内类别编号及名称
    let fDdcCode = ref("");
    let fDdcName = ref("");
    // 打开新增弹框
    // const addData = ()=>{
    //   dialogFormVisible.value = true
    // }

    // 新增提交的fid
    var cursnumber = ref("");

    const curoption = (ev) => {
      let data = treename.filter((item, index) => {
        return item.fDdcName == ev;
      });

      form.fDdcCode = data[0].fDdcCode;
      fl.value = data[0].fId;

      cursnumber.value = data[0].fId;
      fid.value = data[0].fId;
      search_zdcategory(data[0].fId).then((res) => {
        console.log("fDdcCode  res", res);
        fDdcCode.value = res.fDdcCode;
      });
    };
    let fl = ref(null);
    // 新增一条数据
    let newstate = true;
    const newadd = () => {
      let dataObj = {};
      if (isAdd.value) {
        form.fDdcId = fl;
        for (let i in form) {
          dataObj[i] = form[i];
        }
        console.log("结构form", dataObj);
        newPoints({
          ...dataObj,
        })
          .then((res) => {
            //console.log("form:", form);
            //console.log("res:", res);
            dialogFormVisible.value = false;
            getTableData();
          })
          .catch((error) => {
            //console.log(res);
            console.log("error", error);
          });
      } else {
        let flObj = treename.filter((item, index) => {
          return item.fDdcCode == form.fDdcCode;
        });
        console.log(
          "我是trname",
          treename,
          "我是form】",
          form,
          "我是分类对象",
          flObj
        );
        form.fDdcId = flObj[0].fId;
        for (let i in form) {
          dataObj[i] = form[i];
        }
        console.log("dataObj", dataObj);
        dataObj.fCreatorTime = new Date(dataObj.fCreatorTime);
        // pageData.formData.fProductionTime = new Date(
        //   pageData.formData.fProductionTime
        // );
        uppdata({
          ...dataObj,
        }).then((res) => {
          console.log(res);
          getTableData();
          dialogFormVisible.value = false;
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
      }
    };

    let centerDialogVisible = ref(false);
    let delfid = ref("");
    // 删除一条数据
    // const ddthedata = (row) => {
    //   pageData.currentRow = {};
    //   console.log('row',row.row.fState)
    //   if (utils.isEmpty(row.row.fId)) {
    //     ElMessage.warning("请选中需要操作的数据行");
    //     return;
    //   }
    //   deleteData(row.row.fId).then((res) => {
    //     // 调查询数据接口
    //      console.log("res", res);
    //      if ( res.data.msg === '字典已被删除' ){
    //       ElMessage.error("改字典信息已被删除，不可重复删除");
    //      }else{
    //      ElMessageBox.confirm("是否确定删除该字典信息", "提示", {
    //           confirmButtonText: "确定",
    //           cancelButtonText: "取消",
    //           type: "warning",
    //         }).then(() => {
    //           ElMessage.success("删除成功");
    //           getTableData();
    //           // window.location.reload();
    //         }).catch( ()=>{
    //           ElMessage({
    //             type: "info",
    //             message: "删除失败",
    //           });
    //           return
    //         } );
    //         }
    //     // getTableData();

    //   });

    //   centerDialogVisible.value = true;
    //   delfid.value = row.row.fId
    // };
    // 删除
    const ddthedata = (row) => {
      pageData.currentRow = {};
      if (utils.isEmpty(row.row.fId)) {
        ElMessage.warning("请选中需要操作的数据行");
        return;
      }
      if (row.row.fState === 20) {
        ElMessage.error("该字典信息已被删除，不可重复删除");
      } else {
        ElMessageBox.confirm("是否确定删除该字典信息", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            deleteData(row.row.fId).then((res) => {
              console.log(res);
              getTableData();
            });
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除失败",
            });
            return;
          });
      }
      centerDialogVisible.value = true;
      delfid.value = row.row.fId;
    };

    // 分页查询
    const onHandleCurrentChange = (e) => {
      pageData.queryParams.pageIndex = e;
      getTableData();
    };
    const onHandleSizeChange = (e) => {
      pageData.queryParams.pageIndex = 1;
      pageData.queryParams.pageSize = e;
      getTableData();
    };

    const dialogFormVisible = ref(false);
    const dialogForm1Visible = ref(false);
    // 提交表单信息
    const form = reactive({
      fAuditUserId: "",
      fAuditorTime: "", //审核时间，自动生成，非必传
      fBookCode: "", //账套名（获取）
      fCreateUserId: "", //录入人id（自动获取）
      fCreatorTime: "", //录入时间（自动获取）
      fDdCode: "", //字典编码（必传）
      fDdName: "", //字典名称（必传）
      fDdcId: "", //字典分类id（必传，获取目录树分类id）
      fId: "", //字典id(内码，自动生成)
      fLastModifyTime: "",
      fLastModifyUserId: "",
      fRemark: "", //备注
      fState: 0,
      fFullName: null, //状态
    });
    let form1 = reactive({});

    // 编辑一条数据
    const writedata = (row) => {
      console.log(row.row);
      form1 = row.row;
      console.log(form1);
      for (let i in row.row) {
        form1[i] = row.row[i];
      }
      fDdcName.value = row.row.fDdcName;
      fDdcCode.value = row.row.fDdcCode;
      dialogForm1Visible.value = true;
    };

    // 右上角查询输入框
    // 右上角查询输入框
    const onHandleSearch = () => {
      getTableData();
    };
    const onHandleReset = () => {
      pageData.queryParams.fDdCode = "";
      pageData.queryParams.fDdName = "";
      getTableData();
    };
    const value = ref("");

    // 弹窗关闭清空(X)
    // const diaclose = () => {
    //   dialogFormVisible.value = false;
    //   for (let i in form) {
    //     form[i] = "";
    //   }
    // };

    return {
      delfid,
      // sureDelete,
      centerDialogVisible,
      // formLabelWidth,
      onHandleSearch,
      onHandleReset,
      writedata,
      // tree,
      value,
      // defaultProps,
      pageData,
      getTableData,
      dialogFormVisible,
      dialogForm1Visible,
      form,
      //   formInline,
      onHandleCurrentChange,
      onHandleSizeChange,
      handleNodeClick,
      newadd,
      treename,
      ddthedata,
      form1,
      // form2,
      // 新增里面的类别编号、名称
      fDdcCode,
      fDdcName,
      // addData,
      curoption,
      cursnumber,
      props,
      fid,
      newstate,
      // data,
      selectTable,
      addDate,
      fl,
      isAdd,
      // 树
      treeRef,
      treeDate,
      ffun,
    };
  },
};
</script>
<style lang="scss" scoped>
.parent {
  padding: 0;
  margin: 0;
  // 头部页面名称
  .header {
    width: 100%;
    background-color: white;
    user-select: none;

    text-align: left;
    span {
      line-height: 50px;
      font-size: 18px;
      font-weight: 700;
      text-align: left;
      margin-left: 20px;
    }
  }
  .body {
    margin-top: 20px;
    background-color: white;
    height: 77vh;
    // 树形下拉框
    .mainaside {
      background-color: rgb(230, 240, 250);
      border-right: 1px solid #ccc;
    }
    // 内容表格
    .mainmain {
      .firsthe {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .add {
          margin-right: 20px;
        }

        .search {
          display: flex;
          align-items: center;
          user-select: none;

          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>

<style>
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.el-dialog .el-dialog__header {
  padding: 20px 0;
  padding-left: 20px;
  margin: 0;
  /* padding-bottom: 10px; */
  /* margin-right: 16px; */
  word-break: break-all;
  border-bottom: 1px solid #ddd;
  text-align: left;
  /* margin-left: 20px; */
}

.el-select {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-select .el-option {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-input-group__prepend {
  padding: 0 10px;
}
</style>
